package com.colin.jipay.taobao_hook;

import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.GestureDescription;
import android.annotation.TargetApi;
import android.graphics.Path;
import android.graphics.Point;
import android.os.Build;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.Toast;

import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ThreadUtils;
import com.colin.jipay.utils.AccessibilityUtils;
import com.colin.jipay.utils.LogUtil;
import com.colin.jipay.utils.PayHelperUtils;
import com.colin.jipay.utils.SimpleTaskSuccess;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * author    : colin
 * e-mail    : colin12138@gmail.com
 * date      : 2019/7/6 0:04
 * qq        : 1018294974
 */
public class ToOrderDetailSerVice extends AccessibilityService {
    int mX=40 ,mY=140;


    //循环点击微店商户版订单管理里面的代发货按钮，进行刷新的任务
    private SimpleTaskSuccess scheduleClickOrderRefreshTask;


    @TargetApi(Build.VERSION_CODES.N)
    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED){
            String className = (String) event.getClassName();
            LogUtil.log("无障碍服务接收的类名："+className);
            if (className.equals("com.alipay.android.app.flybird.ui.window.FlyBirdWindowActivity")){
                try {
                    Thread.sleep(3000);
                    //findBc();
                    dispatchGestureView(mX,mY);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }else if (className.equals("com.koudai.payment.activity.H5PaymentActivity")
                    || className.equals("com.koudai.payment.activity.PayWeexRenderActivity")) {
                try {
                    Thread.sleep(3000);
                    if (AccessibilityUtils.isFastRefreshPayActivity()) {
                        return;
                    }
                    //点击阿里支付,使用这个功能的时候，必须是支付宝是推荐支付，也就是必须先用支付宝购买过一次商品才行。否则点击位置不准
                    clickPoint(ConvertUtils.dp2px(180), ConvertUtils.dp2px(380));
                    Thread.sleep(600);
                    //点击立即支付
                    clickPoint(ConvertUtils.dp2px(180), ConvertUtils.dp2px(618));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //微店店长版的订单中心
            } else if (className.equals("com.koudai.weishop.order.page.home.OrderHomeActivity")) {
                try {
                    Thread.sleep(3000);
                    scheduleClickOrderRefreshTask = new SimpleTaskSuccess<Object>() {
                        @TargetApi(Build.VERSION_CODES.N)
                        @Override
                        public void onSuccess(@Nullable Object result) {
                            //点击待发货的按钮
                            clickPoint(ConvertUtils.dp2px(33), ConvertUtils.dp2px(218));
                        }
                    };
                    //开始执行刷新的任务
                    ThreadUtils.executeByFixedAtFixRate(4, scheduleClickOrderRefreshTask, 3, TimeUnit.SECONDS);
                } catch (Exception e) {
                    LogUtils.i(e.getMessage());
                }
            } else if (className.equals("com.vdian.android.wdb.order.activity.OrderCenterActivity")) {
                try {
                    //自动确认收货功能
                    autoConfirmReceive(event);
                } catch (Exception e) {
                    LogUtils.i(e.getMessage());
                }

            } else {
                //不在我们要模拟触摸的界面的时候就关闭一些模拟操作任务
                if (scheduleClickOrderRefreshTask != null
                        && !scheduleClickOrderRefreshTask.isCanceled()) {
                    scheduleClickOrderRefreshTask.cancel();
                }
            }
        }
    }

    private void findBc(){
        try{
            AccessibilityNodeInfo info = getRootInActiveWindow();
            for (int i = 0;i<info.getChildCount();i++){
                AccessibilityNodeInfo accessibilityNodeInfo = info.getChild(i);
                if (null != accessibilityNodeInfo.getContentDescription()){

                    String des = accessibilityNodeInfo.getContentDescription().toString();
                    LogUtil.log(des);
                    if (des.contains("返回")){
                        Toast.makeText(this,"zhao",Toast.LENGTH_LONG).show();
                        accessibilityNodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                    }
                }

                LogUtil.log(accessibilityNodeInfo.getClassName().toString());
                if ("android.widget.ImageView".equals(accessibilityNodeInfo.getClassName())){
                    accessibilityNodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                }
            }
        }catch (Exception e){
            LogUtil.log(e.getMessage());
        }

    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    private void dispatchGestureView(int x, int y) {
        Point position = new Point(x, y);
        GestureDescription.Builder builder = new GestureDescription.Builder();
        Path p = new Path();
        p.moveTo(position.x, position.y);
        builder.addStroke(new GestureDescription.StrokeDescription(p, 0L, 1000L));
        GestureDescription gesture = builder.build();
        dispatchGesture(gesture, new GestureResultCallback() {
            @Override
            public void onCompleted(GestureDescription gestureDescription) {
                super.onCompleted(gestureDescription);
                PayHelperUtils.sendmsg(getApplicationContext(),"红包已拆开");
            }

            @Override
            public void onCancelled(GestureDescription gestureDescription) {
                super.onCancelled(gestureDescription);
                PayHelperUtils.sendmsg(getApplicationContext(),"红包未拆开");
            }
        }, null);
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    private void clickPoint(final int x, final int y) {
        Point position = new Point(x, y);
        GestureDescription.Builder builder = new GestureDescription.Builder();
        Path p = new Path();
        p.moveTo(position.x, position.y);
        builder.addStroke(new GestureDescription.StrokeDescription(p, 0L, 200L));
        GestureDescription gesture = builder.build();
        dispatchGesture(gesture, new GestureResultCallback() {
            @Override
            public void onCompleted(GestureDescription gestureDescription) {
                super.onCompleted(gestureDescription);
                LogUtils.i("点击位置", x, y);
            }

            @Override
            public void onCancelled(GestureDescription gestureDescription) {
                super.onCancelled(gestureDescription);
                LogUtils.i("未成功点击位置", x, y);
            }
        }, null);
    }

    @Override
    public void onInterrupt() {

    }

    /**
     * 自动确认收货功能
     *
     * @param event
     * @throws Exception
     */
    @TargetApi(Build.VERSION_CODES.N)
    private void autoConfirmReceive(AccessibilityEvent event) throws Exception {
        Thread.sleep(2000);
        //点击订单中心的待收货按钮
        clickPoint(ConvertUtils.dp2px(247), ConvertUtils.dp2px(100));

        List<AccessibilityNodeInfo> list = event.getSource().findAccessibilityNodeInfosByText("确认收货");

        //确认了有待收货的订单需要处理
        if (null != list && list.size() != 0) {
            Thread.sleep(2000);
            //点击确认收货按钮
            clickPoint(ConvertUtils.dp2px(308), ConvertUtils.dp2px(500));
            Thread.sleep(1000);
            //点击dialog确认按钮
            clickPoint(ConvertUtils.dp2px(250), ConvertUtils.dp2px(385));
            Thread.sleep(2000);
            //点击返回
            clickPoint(ConvertUtils.dp2px(23), ConvertUtils.dp2px(57));
            Thread.sleep(1000);
            //点击dialog退出
            clickPoint(ConvertUtils.dp2px(200), ConvertUtils.dp2px(400));
        }
    }
}
